package com.hjy.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.db.sql.Order;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hjy.auth.vo.MemberEntity;
import com.hjy.common.utils.R;
import com.hjy.order.constant.OrderConstant;
import com.hjy.order.enume.OrderStatusEnum;
import com.hjy.order.feign.CartFeignService;
import com.hjy.order.feign.MemberFeignService;
import com.hjy.order.feign.WareFeignService;
import com.hjy.order.feign.productFeignService;
import com.hjy.order.interceptor.LoginUserInterceptor;
import com.hjy.order.service.OrderItemService;
import com.hjy.order.to.OrderCreateTo;
import com.hjy.order.to.OrderItemEntity;
import com.hjy.order.to.SpuInfoVo;
import com.hjy.order.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjy.common.utils.PageUtils;
import com.hjy.common.utils.Query;

import com.hjy.order.dao.OrderDao;
import com.hjy.order.entity.OrderEntity;
import com.hjy.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    productFeignService productFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private OrderItemService orderItemService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberEntity memberEntity = LoginUserInterceptor.memberEntityThreadLocal.get();
        Long id = memberEntity.getId();
        // 获取当前线程 RequestContextHolder 的内容
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 1. 获取所有地址
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            // 在每个线程中设置一次 RequestContextHolder 的内容
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> addressList = memberFeignService.getAddressList(id);
            orderConfirmVo.setMemberAddressVos(addressList);
        });

        // 2. 获取所有购物车信息
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            // 在每个线程中设置一次 RequestContextHolder 的内容
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();
            orderConfirmVo.setItems(currentCartItems);
        }).thenRunAsync(() -> {
            // 3. 获取库存信息
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R skuHasStock = wareFeignService.getSkuHasStock(collect);
            Object data = skuHasStock.get("data");
            List<SkuStockVo> skuStockVos = JSONUtil.toBean(JSONUtil.toJsonStr(data), new TypeReference<List<SkuStockVo>>() {}, true);
            if (skuStockVos != null) {
                Map<Long, Boolean> collect1 = skuStockVos.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));

                orderConfirmVo.setStocks(collect1);
            }
        });
        // 3. 设置其他
        orderConfirmVo.setIntegration(memberEntity.getIntegration());
        String token = UUID.randomUUID(false).toString();
        // redis 中存储一份
        stringRedisTemplate.opsForValue().set(OrderConstant.ORDER_USER_TOKEN_PREFIX + memberEntity.getId(),token);
        // 前端回显一份
        orderConfirmVo.setOrderToken(token);
        // 4. total 和 payPrice 自动计算
        // 等待异步结果
        CompletableFuture.allOf(future1,future2).join();

        return orderConfirmVo;
    }

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        SubmitOrderResponseVo submitOrderResponseVo = new SubmitOrderResponseVo();
        submitOrderResponseVo.setCode(0);
        // 1. 验证令牌
        String orderToken = orderSubmitVo.getOrderToken();
        MemberEntity memberEntity = LoginUserInterceptor.memberEntityThreadLocal.get();
        String redisToken = OrderConstant.ORDER_USER_TOKEN_PREFIX + memberEntity.getId();
        // 使用 lua 脚本进行验证
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long flag = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(redisToken), orderToken);
        if (flag == 0) {
            // 失败了
            submitOrderResponseVo.setCode(1);
            return submitOrderResponseVo;
        }

        // 2. 创建订单
        OrderCreateTo order = createOrder(orderSubmitVo);
        BigDecimal payPrice = orderSubmitVo.getPayPrice();
        BigDecimal payPrice1 = order.getOrder().getPayAmount();
//        if (!(Math.abs(payPrice1.subtract(payPrice).doubleValue()) < 0.01)) {
//            // 不成功, 价格对比不对
//            submitOrderResponseVo.setCode(2);
//            return submitOrderResponseVo;
//        }

        // 3. 保存数据
        saveOrder(order);
        // 4. 锁定库存
        WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
        wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
        //获取出要锁定的商品数据信息, 这里为了方便使用了 OrderItemVo 类
        List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map((item) -> {
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setSkuId(item.getSkuId());
            orderItemVo.setCount(item.getSkuQuantity());
            orderItemVo.setTitle(item.getSkuName());
            return orderItemVo;
        }).collect(Collectors.toList());
        wareSkuLockVo.setLocks(orderItemVos);
        R r = wareFeignService.orderLockStock(wareSkuLockVo);
        // 判断是否锁库成功的时候到了
        if (r.getCode() == 0) {
            // 成功
            submitOrderResponseVo.setOrder(order.getOrder());
            return submitOrderResponseVo;
        }else if (r.getCode() == 500){
            // 失败, 无库存
            submitOrderResponseVo.setCode(3);
            return submitOrderResponseVo;
        }
        return submitOrderResponseVo;
    }

    @Override
    public PayVo getPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        payVo.setTotal_amount(String.valueOf(order_sn.getPayAmount().setScale(2, BigDecimal.ROUND_HALF_UP)));
        payVo.setOut_trade_no(order_sn.getOrderSn());
        payVo.setSubject("测试");
        payVo.setBody("okk");
        return payVo;
    }

    /**
     * 保存订单
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        //获取订单信息
        com.hjy.order.vo.OrderEntity order1 = order.getOrder();
        order1.setModifyTime(new java.sql.Date(System.currentTimeMillis()));
        order1.setCreateTime(new java.sql.Date(System.currentTimeMillis()));
        //保存订单
        OrderEntity orderEntity = BeanUtil.copyProperties(order1, OrderEntity.class);
        System.out.println("orderEntity = " + orderEntity);
        this.save(orderEntity);

        //获取订单项信息
        List<OrderItemEntity> orderItems = order.getOrderItems();
        //批量保存订单项数据
        List<com.hjy.order.entity.OrderItemEntity> collect = orderItems.stream().map(orderItemEntity -> {
            com.hjy.order.entity.OrderItemEntity orderItemEntity1 = new com.hjy.order.entity.OrderItemEntity();
            BeanUtil.copyProperties(orderItemEntity, orderItemEntity1);
            return orderItemEntity1;
        }).collect(Collectors.toList());
        orderItemService.saveBatch(collect);
    }

    /**
     * 创建 OrderEntityTo 对象
     * @param orderSubmitVo
     * @return
     */
    private OrderCreateTo createOrder(OrderSubmitVo orderSubmitVo) {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1、生成订单号
        String timeId = IdWorker.getTimeId();
        com.hjy.order.vo.OrderEntity orderEntity = builderOrder(timeId, orderSubmitVo);

        //2、获取到所有的订单项
        List<OrderItemEntity> orderItemEntities = builderOrderItems(timeId,orderSubmitVo);
        //3、验价(计算价格、积分等信息)
        computePrice(orderEntity,orderItemEntities);
        // 填充实体类
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);

        return orderCreateTo;
    }

    /**
     * 验价(计算价格、积分等信息)
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(com.hjy.order.vo.OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());
            //总价
            total = total.add(orderItem.getRealAmount());
            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();
        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);
        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);
    }

    /**
     * 构造 OrderEntityItems
     * @param timeId
     * @param orderSubmitVo
     * @return
     */
    private List<OrderItemEntity> builderOrderItems(String timeId, OrderSubmitVo orderSubmitVo) {
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();

        return currentCartItems.stream().map((cartItem) -> {
            //构建订单项数据
            OrderItemEntity orderItemEntity = builderOrderItem(cartItem);
            orderItemEntity.setOrderSn(timeId);
            return orderItemEntity;
        }).collect(Collectors.toList());
    }

    /**
     * 构造 OrderItemEntity 数据
     * @param cartItem
     * @return
     */
    private OrderItemEntity builderOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();

        //1、商品的spu信息
        Long skuId = cartItem.getSkuId();
        //获取spu的信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoData = JSONUtil.toBean(JSONUtil.toJsonStr(spuInfo.get("data")),SpuInfoVo.class);
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandName());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

        //2、商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        orderItemEntity.setSkuQuantity(cartItem.getCount());

        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttrValues = StringUtils.collectionToDelimitedString(cartItem.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        //3、商品的优惠信息

        //4、商品的积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());

        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);
        return orderItemEntity;
    }

    /**
     * 构建 OrderEntity
     * @param orderSn
     * @param orderSubmitVo
     * @return
     */
    private com.hjy.order.vo.OrderEntity builderOrder(String orderSn, OrderSubmitVo orderSubmitVo) {
        MemberEntity memberEntity = LoginUserInterceptor.memberEntityThreadLocal.get();
        R fare = wareFeignService.getFare(orderSubmitVo.getAddrId());
        Object data = fare.get("data");
        FareVo fareVo = JSONUtil.toBean(JSONUtil.toJsonStr(data), FareVo.class);

        com.hjy.order.vo.OrderEntity orderEntity = new com.hjy.order.vo.OrderEntity();
        orderEntity.setMemberId(memberEntity.getId());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberUsername(memberEntity.getUsername());
        //获取到运费信息
        BigDecimal fare1 = fareVo.getFare();
        orderEntity.setFreightAmount(fare1);

        //获取到收货地址信息
        MemberAddressVo address = fareVo.getAddress();
        //设置收货人信息
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());

        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }

}